/*
 * @Author: kanglang
 * @Date: 2021-02-23 11:22:57
 * @LastEditors: kanglang
 * @LastEditTime: 2021-06-08 19:56:07
 * @Description: 第一步 -- 企业信息填写
 */

import React from 'react';
import {
  View,
  StyleSheet,
  Image,
  Text,
  ScrollView,
  NativeModules,
  SafeAreaView,
  TouchableOpacity,
  PixelRatio,
} from 'react-native';
import { Button, msg, FormInput, AsyncStorage, cache } from '@/common';
import {
  px2dp,
  priceColor,
  mainBgColorWhite,
  fontColorBlack,
  fontColorDeepGray,
  mainBgColorLightGray,
  mainBgColorBlack,
} from '@/styles';
import { iconAdd } from '@/images';
import Address from '@/components/address';
import DateTimePicker from 'react-native-modal-datetime-picker';
import Moment from 'moment';
import { uploadImage } from '@/config';
import businessApi from '@/api/business';
import BusinessFormSelect from './components/business-form-select';
import BusinessDateItem from './components/business-date-item';

const { Submit } = Button;

export default class BusinessInfoCerti extends React.Component {
  constructor(props) {
    super(props);
    const { navigation } = props;
    const state = navigation.state || {};
    const params = state.params || {};
    const { routerFrom } = params;
    this.state = {
      longTimeChecked: false,
      selectDateChecked: false,
      visible: false,
      isTimeShow: false,
      entName: '',
      creditCode: '',
      province: '',
      city: '',
      address: '',
      businessScope: '',
      license: '',
      businessFromDate: '',
      businessThruDate: '',
      routerFrom,
    };
  }

  componentDidMount() {
    AsyncStorage.getItem(cache.BUSINESS_INFO_CERTI).then((data) => {
      const dataCache = JSON.parse(data) || {};
      const { businessInfoCerti } = dataCache;
      // const { longTime } = businessInfoCerti;
      this.setState({ ...businessInfoCerti });
    }).catch(err => {
      console.log('企业信息反写异常：', err);
    });
  }

  render() {
    const {
      entName,
      creditCode,
      address,
      businessScope,
      longTimeChecked,
      license,
      visible,
      isTimeShow,
      province,
      city,
      businessFromDate,
      businessThruDate,
      selectDateChecked,
    } = this.state;
    const addAddr = province + city;
    return (
      <SafeAreaView style={styles.container}>
        <ScrollView style={styles.inner}>
          <Text style={styles.stepTip}>第一步</Text>
          <View style={styles.firstPart}>
            <FormInput
              label={this.formItem('企业名称')}
              labelWidth={{ width: px2dp(200) }}
              placeholder='请输入企业名称'
              defaultValue={entName}
              inputType={1}
              maxLength={20}
              textStyles={{ textAlign: 'left' }}
              boxStyle={{ height: 60, paddingLeft: 0 }}
              onChange={(value) => {
                this.onChange('entName', value);
              }}
            />
            <FormInput
              label={this.formItem('社会信用代码')}
              labelWidth={{ width: px2dp(200) }}
              placeholder='请输入社会统一信用代码'
              defaultValue={creditCode}
              inputType={1}
              maxLength={18}
              textStyles={{ textAlign: 'left' }}
              boxStyle={{ height: 60, paddingLeft: 0 }}
              onChange={(value) => {
                this.onChange('creditCode', value);
              }}
            />
            <BusinessFormSelect
              label='经营所在地'
              defaultValue='选择省市区'
              value={addAddr}
              onPress={this.changeAddrBoxVisible}
            />
            <FormInput
              label={this.formItem('经营地址')}
              labelWidth={{ width: px2dp(200) }}
              placeholder='请输入企业详细经营地址'
              defaultValue={address}
              inputType={1}
              textStyles={{ textAlign: 'left' }}
              boxStyle={{ height: 60, paddingLeft: 0 }}
              onChange={(value) => {
                this.onChange('address', value);
              }}
            />
            <BusinessDateItem
              label='经营期限'
              selectDateChecked={selectDateChecked}
              longTimeChecked={longTimeChecked}
              onSwitchLongTime={this.switchChecked}
              onSwitchSelectDate={this.switchDateChecked}
              onStartDate={() => {
                this.setState({
                  isTimeShow: true,
                  isTimeType: 'businessFromDate',
                });
              }}
              onEndDate={() => {
                this.setState({
                  isTimeShow: true,
                  isTimeType: 'businessThruDate',
                });
              }}
              startTip={businessFromDate}
              endTip={businessThruDate}
            />
            <FormInput
              label={this.formItem('经营范围')}
              labelWidth={{ width: px2dp(200) }}
              placeholder='请输入企业营业范围'
              defaultValue={businessScope}
              inputType={1}
              multiline
              numberOfLines={3}
              textStyles={{ textAlign: 'left' }}
              boxStyle={{ minHeight: 60, borderBottomColor: 'transparent', paddingLeft: 0 }}
              onChange={(value) => {
                this.onChange('businessScope', value);
              }}
            />
          </View>
          <View style={styles.licenseBox}>
            <View style={styles.labelBox}>{this.formItem('上传营业执照')}</View>
            <View style={styles.licenseBtnBox}>
              <TouchableOpacity onPress={this.selectImage}>
                {license ? (
                  <Image
                    style={styles.licenseImgStyle}
                    source={{ uri: license }}
                  />
                ) : (
                  <View style={styles.defaultAddBox}>
                    <Image style={styles.addImgIcon} source={iconAdd} />
                  </View>
                )}
              </TouchableOpacity>
            </View>
          </View>
          <View style={styles.bottomBtnBox}>
            <View style={styles.submitBox}>
              <Submit
                text='上一步'
                btnTextStyle={styles.preStepText}
                boxStyle={styles.preBoxStyle}
                onClick={this.goBack}
              />
            </View>
            <View style={styles.submitBox}>
              <Submit
                text='下一步'
                btnTextStyle={styles.nextStepText}
                boxStyle={styles.nextBoxStyle}
                onClick={this.goNext}
              />
            </View>
          </View>
          <Address
            visible={visible}
            level={3}
            getAdressData={(data) => this.getAddressData(data)}
            changeVisible={this.changeAddrBoxVisible}
          />
          <DateTimePicker
            isVisible={isTimeShow}
            mode='date'
            cancelTextIOS='取消'
            confirmTextIOS='确认'
            headerTextIOS='选取日期'
            locale='zh_CN'
            onConfirm={(val) => {
              this.dateConfirm(val);
            }}
            onCancel={() => {
              this.dateCancel();
            }}
          />
        </ScrollView>
      </SafeAreaView>
    );
  }

  formItem = (name) => {
    return (
      <>
        <Text style={{ color: priceColor }}>＊</Text>
        <Text style={{ color: fontColorDeepGray, fontSize: px2dp(28) }}>
          {name}
        </Text>
      </>
    );
  };

  // 选择长期
  switchChecked = () => {
    const { longTimeChecked } = this.state;
    this.setState({ longTimeChecked: !longTimeChecked }, () => {
      const { longTimeChecked } = this.state;
      if (longTimeChecked) {
        this.setState({ selectDateChecked: false, businessThruDate: '长期' });
      }
    });
  };

  // 选择日期
  switchDateChecked = () => {
    const { selectDateChecked } = this.state;
    this.setState(
      { selectDateChecked: !selectDateChecked, longTimeChecked: false },
      () => {
        const { selectDateChecked } = this.state;
        if (!selectDateChecked) {
          this.setState({ businessFromDate: '', businessThruDate: '' });
        } else {
          this.setState({ businessThruDate: '' });
        }
      },
    );
  };

  goBack = () => {
    msg.emit('router: back');
  };

  goNext = () => {
    const {
      entName,
      creditCode,
      address,
      businessScope,
      longTimeChecked,
      license,
      province,
      city,
      businessFromDate,
      businessThruDate,
      selectDateChecked,
      routerFrom,
    } = this.state;
    if (!entName) return msg.emit('app:tip', { text: '请填写企业名称' });
    if (!creditCode) return msg.emit('app:tip', { text: '请填写社会信用代码' });
    if (creditCode.length != 18) { return msg.emit('app:tip', { text: '请填写正确的社会信用代码' }); }
    if (!province || !city) return msg.emit('app:tip', { text: '请选择省市' });
    if (!address) return msg.emit('app:tip', { text: '请填写企业详细经营地址' });
    if ((!businessFromDate || !businessThruDate) && !longTimeChecked) { return msg.emit('app:tip', { text: '请选择经营期限日期' }); }
    if (longTimeChecked && !businessFromDate) { return msg.emit('app:tip', { text: '请选择经营期限起始日期' }); }
    if (!businessScope) { return msg.emit('app:tip', { text: '请填写企业经营范围' }); }
    if (!license) return msg.emit('app:tip', { text: '请上传营业执照' });
    businessApi.checkLegalName({ entName }).then((res) => {
      if (res.success && res.data) {
        const businessInfoCertiCache = {
          entName,
          creditCode,
          province,
          city,
          address,
          businessFromDate,
          businessThruDate,
          longTimeChecked, // 是否选择长期
          selectDateChecked, // 是否选择的是日期
          longTime: longTimeChecked ? 1 : 0,
          businessScope,
          license,
        };
        const businessCertiString = JSON.stringify({
          businessInfoCerti: businessInfoCertiCache,
        });
        AsyncStorage.setItem(
          cache.BUSINESS_INFO_CERTI,
          businessCertiString
        );
        msg.emit('router: goToNext', {
          routeName: 'LegalInfoCerti',
          routerFrom,
        });
      } else {
        msg.emit('app:tip', { text: '该企业名称已存在' });
      }
    });
  };

  // 输入框变化监听
  onChange = (type, value) => {
    this.setState({ [type]: value });
  };

  // 隐藏地址选择框
  changeAddrBoxVisible = () => {
    const { visible } = this.state;
    this.setState({ visible: !visible });
  };

  // 选择地址回调
  getAddressData = (address) => {
    address.list.map((v, i) => {
      if (v.type == 'province') {
        this.setState({ province: v.name });
      }

      if (v.type == 'city') {
        this.setState({ city: v.name });
      }
      // if(v.type == 'county'){
      //     this.setState({county:v.name});
      // }
    });
  };

  // 日期选择后确认
  dateConfirm = (date) => {
    const { isTimeType } = this.state;
    this.setState({ [isTimeType]: Moment(date).format('YYYY-MM-DD') });
    this.setState({ isTimeShow: false });
  };

  // 隐藏日期选择器
  dateCancel = () => {
    this.setState({ isTimeShow: false });
  };

  // 选择图片
  selectImage = () => {
    NativeModules.DataModule.chooseImage((path, imageBase64) => {
      this.IdCardUpload(path);
    });
  };

  // 上传图片
  IdCardUpload(path) {
    msg.emit('app:selfTip', {
      isVisible: true,
      text: '图片上传中...',
      icon: 'loading',
      style: { zIndex: 1 }
    });
    uploadImage('upload?dirName=businessCert', path)
      .then((res) => {
        console.log(`uploadImage：${JSON.stringify(res)}`);
        if (res.success) {
          this.setState({ license: res.data.url });
        } else {
          console.log('==================>', res);
        }
        msg.emit('app:selfTip', {
          isVisible: false,
        });
      })
      .catch((err) => {
        console.log('err', err);
        msg.emit('app:selfTip', {
          isVisible: false,
        });
        // 请求失败
        msg.emit('app:messageBox', {
          isVisible: true,
          title: '温馨提示',
          text: '上传出错，请重试',
          okText: '确定',
        });
      });
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: mainBgColorWhite,
  },
  inner: {
    flex: 1,
    backgroundColor: mainBgColorLightGray,
  },
  stepTip: {
    color: mainBgColorBlack,
    fontSize: px2dp(28),
    paddingLeft: px2dp(32),
    paddingVertical: px2dp(24),
  },
  firstPart: {
    backgroundColor: mainBgColorWhite,
    paddingHorizontal: px2dp(32),
    paddingBottom: px2dp(60),
  },
  fontTitle: {
    color: fontColorBlack,
    fontSize: px2dp(32),
    marginTop: px2dp(32),
    lineHeight: px2dp(40),
  },
  fontText: {
    color: fontColorBlack,
    fontSize: px2dp(28),
    lineHeight: px2dp(38),
  },
  tempText: {
    color: '#2293FF',
    fontSize: px2dp(28),
    textDecorationLine: 'underline',
  },
  btnBox: {
    flex: 1,
    alignItems: 'center',
    marginTop: px2dp(130),
  },
  boxStyle: {
    width: px2dp(640),
    height: px2dp(96),
    borderRadius: px2dp(12),
    overflow: 'hidden',
  },
  longTimeBox: {
    flexDirection: 'row',
    marginRight: px2dp(40),
  },
  longTime: {
    color: '#b2b2b2',
    marginLeft: px2dp(16),
  },
  itemBox: {
    flexDirection: 'row',
    alignItems: 'center',
    borderBottomWidth: 1 / PixelRatio.get(),
    borderBottomColor: '#ebebeb',
    width: '100%',
    height: 60,
  },
  labelBox: {
    flexDirection: 'row',
    alignItems: 'center',
    width: px2dp(190),
  },
  addressBox: {
    flexDirection: 'row',
    alignItems: 'center',
    marginLeft: px2dp(10),
  },
  addressImgBox: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  iconMore: {
    width: px2dp(24),
    height: px2dp(24),
    marginLeft: px2dp(16),
  },
  timeImg: {
    width: px2dp(36),
    height: px2dp(36),
    marginRight: px2dp(16),
  },
  licenseBox: {
    justifyContent: 'space-between',
    backgroundColor: mainBgColorWhite,
    paddingHorizontal: px2dp(32),
    paddingVertical: px2dp(40),
    marginTop: px2dp(24),
  },
  licenseBtnBox: {
    flexDirection: 'row',
    alignItems: 'center',
    width: px2dp(190),
    marginTop: px2dp(40),
    paddingLeft: px2dp(32),
  },
  licenseImgStyle: {
    width: px2dp(160),
    height: px2dp(160),
  },
  defaultAddBox: {
    width: px2dp(160),
    height: px2dp(160),
    backgroundColor: mainBgColorLightGray,
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: px2dp(8),
  },
  addImgIcon: {
    width: px2dp(48),
    height: px2dp(48),
  },
  bottomBtnBox: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    height: px2dp(200),
    marginTop: px2dp(40),
  },
  submitBox: {
    flex: 1,
    alignItems: 'center',
  },
  preStepText: {
    fontSize: px2dp(32),
    color: '#686764',
  },
  nextStepText: {
    fontSize: px2dp(32),
  },
  preBoxStyle: {
    width: px2dp(280),
    borderRadius: px2dp(12),
    backgroundColor: '#E6E6E5',
  },
  nextBoxStyle: {
    width: px2dp(280),
    borderRadius: px2dp(12),
  },
  addressText: {
    color: '#b2b2b2',
    maxWidth: '80%',
  },
});
